from xml.dom import minidom
import gbase

def requireAttribute(name):
  """Generates a query that will require the given attribute
  to be present.

  Args:
    name: attribute name

  Returns:
    a string of the form "[attributename]"
  """


def xmlname(name):
  """Generates the XML tag name given an attribute name.

  Args:
    name: attribute name, with spaces

  Returns:
    XML tag name, with underscores instead of spaces
  """
  return name.replace(' ', '_')

def toxml(domTree):
  """Generates a nice XML representation for a DOM tree.

  Args:
    domTree: DOM tree (document or element)
  Returns:
    Nice textual representation
  """
  return domTree.toprettyxml(indent="  ", encoding="utf-8")


def getFeedEntries(feed):
  """Extracts the entry/entries from an atom feed.

  Args:
    feed: atom feed, a DOM document
  Returns:
    a list of DOM elements 'entry', which might be empty
  """
  return feed.getElementsByTagNameNS(gbase.ATOM_NAMESPACE_URI,
                                     "entry")

def getSingleValue(parent, tag_name):
  ret = ''
  nodes = parent.getElementsByTagName(tag_name)
  if len(nodes) > 0:
    children = nodes[0].childNodes
    for child in children:
      ret += str(child.data)
  
  return ret

def getEntryID(entry):
  return getSingleValue(entry, 'id')

def getEntryContent(entry):
  return getSingleValue(entry, 'content')

def getExpireDate(entry):
  return getSingleValue(entry, 'g:expiration_date')

def getFileName(entry):
  return getSingleValue(entry, 'g:filename')
